<template>
  <div
    class="w-full md:w-3/4 flex-1 flex flex-col rounded-2xl shadow-md bg-gradient-to-br p-6 from-white to-gray-100 dark:from-gray-900 dark:to-gray-800"
  >
    <ArticleHeader
      v-if="isArticle"
      :title="article.title"
      :create-time="article.createTime"
      :count-md="countMd"
      :reading-minutes="readingMinutes"
      :image-count="imageCount"
      :visit-count="article.visitCount"
    />
    <ArticleHeaderSkeleton v-else />
    <ElDivider class="border-gray-900 dark:border-gray-500" />
    <MdPreview
      v-if="isArticle"
      class="bg-gradient-to-br pl-1 pr-1 pb-2 from-white to-gray-100 dark:from-gray-900 dark:to-gray-800"
      :editorId="id"
      :modelValue="article.content"
      :on-html-changed="mdHtml"
      :theme="mode"
    />
    <MdPreviewSkeleton v-else />
    <ArticleBottom v-if="article" :article="article" />
    <ArticleBottomSkeleton v-else />
  </div>
</template>
<script lang="ts" setup>
import { MdPreview } from 'md-editor-v3'
import { useColorMode } from '@vueuse/core'
const props = defineProps<{
  id: string
  article: any
}>()
const isArticle = computed(() => !!props.article && !!props.article.title)

const { article } = toRefs(props)
const mode = useColorMode({ storageKey: 'user-theme' })
// 字数 统计
const countMd = ref(0)
const readingMinutes = ref(0)
const imageCount = ref(0)
function mdHtml(htmlText: string) {
  const text = htmlText
    .replace(/<[^>]+>/g, '')
    .replace(/[\r\n]/g, '')
    .replace(/[ ]/g, '')
    .replace(/[\s+\.\!\/_,$%^*(+\"\']+|[+——！，。？、~@#￥%……&*（）]+/g, '')

  const wordCount = text.length
  countMd.value = <number>countWords(text.length)
  readingMinutes.value = Math.max(1, Math.ceil(wordCount / 300))
  imageCount.value = countImages(htmlText)
}
function countImages(htmlText: string): number {
  const imgTagRegex = /<img [^>]*src=['"]([^'"]+)['"][^>]*>/gi
  const matches = htmlText.match(imgTagRegex)
  return matches ? matches.length : 0
}

// 字数统计
function countWords(count: number) {
  if (count <= 1000) {
    return count
  } else {
    let counts = count / 1000
    // 留小数点一位数
    counts = Number(counts.toFixed(1))
    return counts + 'k'
  }
}
</script>
